<template>
  <div class="student-management">
    <div class="page-header">
      <h2>学生管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="学号">
          <el-input
            v-model="searchForm.stuNo"
            placeholder="请输入学号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="院系">
          <el-input
            v-model="searchForm.stuDept"
            placeholder="请输入院系"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="学生姓名">
          <el-input
            v-model="searchForm.stuName"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.stuSex"
            placeholder="请选择性别"
            clearable
            style="width: 150px"
          >
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.stuPhone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增学生
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="studentList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="stuNo" label="学号" width="120" />
        <el-table-column prop="stuName" label="学生姓名" width="120" />
        <el-table-column prop="stuAge" label="年龄" width="120" />
        <el-table-column prop="stuSex" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.stuSex === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
          <el-table-column prop="stuDept" label="院系" width="140" />
        <el-table-column prop="stuPhone" label="手机号" width="150" />
        <el-table-column prop="stuEmail" label="邮箱" width="200" />
        <el-table-column prop="stuQq" label="QQ" width="120" />
        <el-table-column prop="stuRemark" label="备注" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="stuNo">
          <el-input v-model="form.stuNo" placeholder="请输入学号" />
        </el-form-item>
        
        <el-form-item label="学生姓名" prop="stuName">
          <el-input v-model="form.stuName" placeholder="请输入学生姓名" />
        </el-form-item>

        <el-form-item label="年龄" prop="stuAge">
          <el-input v-model.number="form.stuAge" placeholder="请输入年龄" />
        </el-form-item>
        
        <el-form-item label="性别" prop="stuSex">
          <el-select v-model="form.stuSex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="手机号" prop="stuPhone">
          <el-input v-model="form.stuPhone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="院系" prop="stuDept">
          <el-input v-model="form.stuDept" placeholder="请输入院系" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="stuEmail">
          <el-input v-model="form.stuEmail" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="QQ" prop="stuQq">
          <el-input v-model="form.stuQq" placeholder="请输入QQ号" />
        </el-form-item>
        
        <el-form-item label="备注" prop="stuRemark">
          <el-input 
            v-model="form.stuRemark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="学生详情"
      width="600px"
    >
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">
            {{ detailData.stuNo }}
          </el-descriptions-item>
          <el-descriptions-item label="学生姓名">
            {{ detailData.stuName }}
          </el-descriptions-item>
          
          <el-descriptions-item label="年龄">
            {{ detailData.stuAge }}
          </el-descriptions-item>

          <el-descriptions-item label="性别">
            {{ detailData.stuSex === 1 ? '男' : '女' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ detailData.stuPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="院系">
            {{ detailData.stuDept || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ detailData.stuEmail }}
          </el-descriptions-item>
          <el-descriptions-item label="QQ">
            {{ detailData.stuQq }}
          </el-descriptions-item>
          <el-descriptions-item label="修改时间" :span="2">
            {{ formatDate(detailData.stuUpdateDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ detailData.stuRemark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getStudentList, getStudentDetail, addStudent, updateStudent, deleteStudent } from '../api/student'

// 搜索表单数据
const searchForm = reactive({
  stuNo: '', // 学号
  stuName: '', // 学生姓名
  stuSex: '', // 性别
  stuPhone: '', // 电话
  stuDept: '' // 院系
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const studentList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const detailData = ref({})

// 表单数据
const form = reactive({
  studentId: null,
  stuNo: '', // 学号
  stuName: '', // 学生姓名
  stuSex: '', // 性别 (1-男, 2-女)
  stuPhone: '', // 电话
  stuDept: '', // 院系
  stuEmail: '', // 邮箱
  stuQq: '', // QQ
  stuRemark: '' // 备注
})

// 表单验证规则
const rules = {
  stuNo: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  stuName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' }
  ],
  stuSex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  stuPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  stuEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  stuQq: [
    { pattern: /^[1-9]\d{4,10}$/, message: '请输入正确的QQ号', trigger: 'blur' }
  ]
}

const formRef = ref()

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchStudentList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.currentPage = 1
  fetchStudentList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增学生'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    // 从后端获取最新的学生详情
    const response = await getStudentDetail(parseInt(row.studentId))
    if (response.data) {
      detailData.value = response.data
    } else {
      // 如果接口失败，使用当前行数据
      detailData.value = { ...row }
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取学生详情失败:', error)
    // 接口失败时使用当前行数据
    detailData.value = { ...row }
    detailDialogVisible.value = true
  }
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑学生'
  isEdit.value = true
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除学生 "${row.stuName}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 后端接口需要Integer类型的id
      await deleteStudent(parseInt(row.studentId))
      ElMessage.success('删除成功')
      fetchStudentList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const handleSubmit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    try {
      if (isEdit.value) {
        // 编辑时传递完整的form对象，包含studentId
        await updateStudent(form)
        ElMessage.success('编辑成功')
      } else {
        // 新增时不需要传递studentId
        const { studentId, ...addData } = form
        await addStudent(addData)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchStudentList()
    } catch (error) {
      console.error('操作失败:', error)
    }
  }
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
  formRef.value?.resetFields()
}

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    form[key] = key === 'studentId' ? null : ''
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchStudentList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchStudentList()
}

// 获取学生列表
const fetchStudentList = async () => {
  loading.value = true
  
  try {
    // 确保所有参数都有值
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      stuNo: searchForm.stuNo !== undefined && searchForm.stuNo !== '' ? searchForm.stuNo : -1,
      stuName: searchForm.stuName || '',
      stuSex: searchForm.stuSex !== undefined && searchForm.stuSex !== '' ? searchForm.stuSex : -1,
      stuPhone: searchForm.stuPhone || '',
      stuDept: searchForm.stuDept || ''
    }
    
    console.log('组件发送参数:', params) // 调试用
    console.log('搜索表单数据:', searchForm) // 调试用
    
    const response = await getStudentList(params)
    
    // 根据后端接口返回的数据结构进行调整
    // 后端返回: Result<Map<String, Object>>，包含分页信息
    if (response.data) {
      studentList.value = response.data.records || response.data.list || []
      pagination.total = response.data.total || 0
    } else {
      studentList.value = []
      pagination.total = 0
    }
    
  } catch (error) {
    console.error('获取学生列表失败:', error)
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStudentList()
})
</script>

<style scoped>
.student-management {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.search-card :deep(.el-card__body) {
  padding: 20px;
}

.search-form {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 24px;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.search-form :deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.search-form :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

.search-form :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.search-form :deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.search-form :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.search-form :deep(.el-button--primary) {
  background: #409eff;
  border-color: #409eff;
}

.search-form :deep(.el-button--primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

.search-form :deep(.el-button:not(.el-button--primary)) {
  background: #ffffff;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.search-form :deep(.el-button:not(.el-button--primary):hover) {
  background: #ecf5ff;
  color: #409eff;
  border-color: #c6e2ff;
}

.action-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.action-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
}

.action-buttons :deep(.el-button--primary) {
  background: #67c23a;
  border-color: #67c23a;
  border-radius: 4px;
  padding: 10px 20px;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.3s ease;
}

.action-buttons :deep(.el-button--primary:hover) {
  background: #85ce61;
  border-color: #85ce61;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.table-card :deep(.el-table) {
  border-radius: 0;
}

.table-card :deep(.el-table__header) {
  background: #f5f7fa;
}

.table-card :deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
  padding: 12px;
}

.table-card :deep(.el-table td) {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.table-card :deep(.el-table__row:hover) {
  background: #f5f7fa;
}

.table-card :deep(.el-table__row:nth-child(even)) {
  background: #fafafa;
}

.table-card :deep(.el-table__row:nth-child(even):hover) {
  background: #f5f7fa;
}

.table-card :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.table-card :deep(.el-button--primary) {
  background: #409eff;
  border-color: #409eff;
}

.table-card :deep(.el-button--primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

.table-card :deep(.el-button--danger) {
  background: #f56c6c;
  border-color: #f56c6c;
}

.table-card :deep(.el-button--danger:hover) {
  background: #f78989;
  border-color: #f78989;
}

.pagination-container {
  margin-top: 16px;
  padding: 16px 20px;
  display: flex;
  justify-content: center;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.pagination-container :deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #606266;
  --el-pagination-border-radius: 4px;
}

.pagination-container :deep(.el-pagination .btn-prev),
.pagination-container :deep(.el-pagination .btn-next) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background: #ffffff;
  color: #606266;
  transition: all 0.3s ease;
}

.pagination-container :deep(.el-pagination .btn-prev:hover),
.pagination-container :deep(.el-pagination .btn-next:hover) {
  background: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.pagination-container :deep(.el-pager li) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background: #ffffff;
  color: #606266;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-container :deep(.el-pager li:hover) {
  background: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.pagination-container :deep(.el-pager li.is-active) {
  background: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

.dialog-footer :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.dialog-footer :deep(.el-button--primary) {
  background: #409eff;
  border-color: #409eff;
}

.dialog-footer :deep(.el-button--primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
}

:deep(.el-dialog__header) {
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 0 0 8px 8px;
  border-top: 1px solid #ebeef5;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

/* 详情对话框样式 */
.detail-content {
  padding: 20px 0;
}

.detail-content :deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

.detail-content :deep(.el-descriptions__header) {
  background: #f5f7fa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-content :deep(.el-descriptions__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.detail-content :deep(.el-descriptions__body) {
  background: #ffffff;
}

.detail-content :deep(.el-descriptions-item__label) {
  background: #fafafa;
  color: #606266;
  font-weight: 600;
  width: 120px;
}

.detail-content :deep(.el-descriptions-item__content) {
  color: #2c3e50;
  padding: 12px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .student-management {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
  
  .search-form :deep(.el-input),
  .search-form :deep(.el-select) {
    width: 100%;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .pagination-container {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .student-management {
    padding: 12px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .search-card :deep(.el-card__body),
  .action-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .table-card :deep(.el-table th),
  .table-card :deep(.el-table td) {
    padding: 12px 8px;
    font-size: 13px;
  }
}
</style>

